{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 基于SVD的协同过滤"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 导入工具包"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "# load数据（用户和物品索引，以及倒排表）\n",
    "import _pickle as cPickle\n",
    "import json\n",
    "\n",
    "from numpy.random import random\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 读入数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 用户和item的索引\n",
    "users_index = cPickle.load(open(\"./out/users_index.pkl\", 'rb'))\n",
    "items_index = cPickle.load(open(\"./out/items_index.pkl\", 'rb'))\n",
    "\n",
    "n_users = len(users_index)\n",
    "n_items = len(items_index)\n",
    "    \n",
    "# 倒排表\n",
    "# 每个用户打过分的电影\n",
    "user_items = cPickle.load(open(\"./out/user_items.pkl\", 'rb'))\n",
    "# 对每个电影打过分的事用户\n",
    "item_users = cPickle.load(open(\"./out/item_users.pkl\", 'rb'))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   user_id  item_id  rating\n",
      "0        1        1       5\n",
      "1        1        2       3\n",
      "2        1        3       4\n",
      "3        1        4       3\n",
      "4        1        5       3\n"
     ]
    }
   ],
   "source": [
    "# 读取训练数据\n",
    "triplet_cols = ['user_id','item_id', 'rating', 'timestamp'] \n",
    "\n",
    "dpath = './data/u1.base'\n",
    "df_triplet = pd.read_csv(dpath, \n",
    "                         sep='\\t', \n",
    "                         names=triplet_cols, \n",
    "                         encoding='latin-1')\n",
    "df_triplet = df_triplet.drop(['timestamp'], axis=1)\n",
    "\n",
    "print(df_triplet.head())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 初始化模型参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 隐含变量的维数\n",
    "K = 40\n",
    "\n",
    "# r(ui) = \\mu + bu + bi + Pu'T Qi\n",
    "\n",
    "# Item和User的偏置项\n",
    "bi = np.zeros((n_items, 1))\n",
    "bu = np.zeros((n_users, 1))\n",
    "\n",
    "# Item和User的隐含向量\n",
    "qi = np.zeros((n_items, K))    \n",
    "pu = np.zeros((n_users, K))   \n",
    "\n",
    "for uid in range(n_users):\n",
    "    pu[uid] = np.reshape(random((K, 1)) / 10 * np.sqrt(K), K)\n",
    "       \n",
    "for iid in range(n_items):\n",
    "    qi[iid] = np.reshape(random((K, 1)) / 10 * np.sqrt(K), K)\n",
    "\n",
    "# 所有用户的平均打分\n",
    "mu = df_triplet['rating'].mean()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 根据当前参数，预测用户uid对Item（i_id）的打分"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def svd_pred(uid, iid):  \n",
    "    score = mu + bi[iid] + bu[uid] + np.sum(qi[iid] * pu[uid]) \n",
    "    return score\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 模型训练"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "开始进行50个step的训练\n",
      "The 0-th  step is running\n",
      "完成第1个step的训练, rmse=[1.18058585], 耗时41.8464秒\n",
      "The 1-th  step is running\n",
      "完成第2个step的训练, rmse=[0.9270805], 耗时41.7024秒\n",
      "The 2-th  step is running\n",
      "完成第3个step的训练, rmse=[0.90726438], 耗时41.5924秒\n",
      "The 3-th  step is running\n",
      "完成第4个step的训练, rmse=[0.89555945], 耗时41.7614秒\n",
      "The 4-th  step is running\n",
      "完成第5个step的训练, rmse=[0.88663799], 耗时41.5904秒\n",
      "The 5-th  step is running\n",
      "完成第6个step的训练, rmse=[0.87725411], 耗时41.6154秒\n",
      "The 6-th  step is running\n",
      "完成第7个step的训练, rmse=[0.87025475], 耗时41.7684秒\n",
      "The 7-th  step is running\n",
      "完成第8个step的训练, rmse=[0.86404012], 耗时41.5764秒\n",
      "The 8-th  step is running\n",
      "完成第9个step的训练, rmse=[0.85778955], 耗时41.6064秒\n",
      "The 9-th  step is running\n",
      "完成第10个step的训练, rmse=[0.85265384], 耗时41.4864秒\n",
      "The 10-th  step is running\n",
      "完成第11个step的训练, rmse=[0.84856777], 耗时41.6094秒\n",
      "The 11-th  step is running\n",
      "完成第12个step的训练, rmse=[0.84451892], 耗时41.6154秒\n",
      "The 12-th  step is running\n",
      "完成第13个step的训练, rmse=[0.84105291], 耗时41.8264秒\n",
      "The 13-th  step is running\n",
      "完成第14个step的训练, rmse=[0.83839413], 耗时41.9524秒\n",
      "The 14-th  step is running\n",
      "完成第15个step的训练, rmse=[0.83543897], 耗时41.5984秒\n",
      "The 15-th  step is running\n",
      "完成第16个step的训练, rmse=[0.83309249], 耗时41.9204秒\n",
      "The 16-th  step is running\n",
      "完成第17个step的训练, rmse=[0.83090809], 耗时41.6524秒\n",
      "The 17-th  step is running\n",
      "完成第18个step的训练, rmse=[0.82885146], 耗时41.6834秒\n",
      "The 18-th  step is running\n",
      "完成第19个step的训练, rmse=[0.82715086], 耗时41.8244秒\n",
      "The 19-th  step is running\n",
      "完成第20个step的训练, rmse=[0.82529596], 耗时41.7094秒\n",
      "The 20-th  step is running\n",
      "完成第21个step的训练, rmse=[0.8239932], 耗时41.6104秒\n",
      "The 21-th  step is running\n",
      "完成第22个step的训练, rmse=[0.82256499], 耗时41.7044秒\n",
      "The 22-th  step is running\n",
      "完成第23个step的训练, rmse=[0.82124946], 耗时41.7554秒\n",
      "The 23-th  step is running\n",
      "完成第24个step的训练, rmse=[0.82003843], 耗时41.7624秒\n",
      "The 24-th  step is running\n",
      "完成第25个step的训练, rmse=[0.81899814], 耗时41.8984秒\n",
      "The 25-th  step is running\n",
      "完成第26个step的训练, rmse=[0.81793132], 耗时41.7614秒\n",
      "The 26-th  step is running\n",
      "完成第27个step的训练, rmse=[0.81715274], 耗时41.8804秒\n",
      "The 27-th  step is running\n",
      "完成第28个step的训练, rmse=[0.8162825], 耗时41.7094秒\n",
      "The 28-th  step is running\n",
      "完成第29个step的训练, rmse=[0.81544997], 耗时41.8024秒\n",
      "The 29-th  step is running\n",
      "完成第30个step的训练, rmse=[0.81473627], 耗时41.7464秒\n",
      "The 30-th  step is running\n",
      "完成第31个step的训练, rmse=[0.81419161], 耗时41.5944秒\n",
      "The 31-th  step is running\n",
      "完成第32个step的训练, rmse=[0.81347666], 耗时41.7294秒\n",
      "The 32-th  step is running\n",
      "完成第33个step的训练, rmse=[0.81287154], 耗时41.4564秒\n",
      "The 33-th  step is running\n",
      "完成第34个step的训练, rmse=[0.81232654], 耗时41.5754秒\n",
      "The 34-th  step is running\n",
      "完成第35个step的训练, rmse=[0.81191833], 耗时41.5164秒\n",
      "The 35-th  step is running\n",
      "完成第36个step的训练, rmse=[0.81144414], 耗时41.5674秒\n",
      "The 36-th  step is running\n",
      "完成第37个step的训练, rmse=[0.81100497], 耗时41.8414秒\n",
      "The 37-th  step is running\n",
      "完成第38个step的训练, rmse=[0.81069703], 耗时41.8644秒\n",
      "The 38-th  step is running\n",
      "完成第39个step的训练, rmse=[0.81026707], 耗时41.6944秒\n",
      "The 39-th  step is running\n",
      "完成第40个step的训练, rmse=[0.80993264], 耗时41.6474秒\n",
      "The 40-th  step is running\n",
      "完成第41个step的训练, rmse=[0.80959347], 耗时41.6014秒\n",
      "The 41-th  step is running\n",
      "完成第42个step的训练, rmse=[0.8093159], 耗时41.6124秒\n",
      "The 42-th  step is running\n",
      "完成第43个step的训练, rmse=[0.80910571], 耗时41.6074秒\n",
      "The 43-th  step is running\n",
      "完成第44个step的训练, rmse=[0.80879311], 耗时41.7154秒\n",
      "The 44-th  step is running\n",
      "完成第45个step的训练, rmse=[0.80862828], 耗时41.8024秒\n",
      "The 45-th  step is running\n",
      "完成第46个step的训练, rmse=[0.80837109], 耗时41.6534秒\n",
      "The 46-th  step is running\n",
      "完成第47个step的训练, rmse=[0.80819926], 耗时41.6784秒\n",
      "The 47-th  step is running\n",
      "完成第48个step的训练, rmse=[0.808019], 耗时41.7974秒\n",
      "The 48-th  step is running\n",
      "完成第49个step的训练, rmse=[0.80779787], 耗时41.5034秒\n",
      "The 49-th  step is running\n",
      "完成第50个step的训练, rmse=[0.80766296], 耗时41.7224秒\n",
      "结束了50个step的训练，总耗时2084.7492秒\n"
     ]
    }
   ],
   "source": [
    "# gamma：为学习率\n",
    "# Lambda：正则参数\n",
    "# steps：迭代次数\n",
    "import time\n",
    "\n",
    "steps = 50\n",
    "gamma = 0.04\n",
    "Lambda = 0.15\n",
    "\n",
    "# 总的打分记录数目\n",
    "n_records = df_triplet.shape[0]\n",
    "\n",
    "time_start = time.time()\n",
    "\n",
    "print(\"开始进行{}个step的训练\".format(steps))\n",
    "\n",
    "each_time_start = time_start\n",
    "for step in range(steps):\n",
    "    print('The {}-th  step is running'.format(step))\n",
    "    rmse_sum = 0.0\n",
    "            \n",
    "    # 将训练样本打散顺序\n",
    "    kk = np.random.permutation(n_records)  \n",
    "    for j in range(n_records):\n",
    "        # 每次一个训练样本\n",
    "        line = kk[j]\n",
    "        \n",
    "        uid = users_index[df_triplet.iloc[line]['user_id']]\n",
    "        iid = items_index[df_triplet.iloc[line]['item_id']]\n",
    "        rating = df_triplet.iloc[line]['rating']\n",
    "\n",
    "        # 预测残差\n",
    "        eui = rating - svd_pred(uid, iid)\n",
    "        # 残差平方和\n",
    "        rmse_sum += eui**2\n",
    "\n",
    "        # 随机梯度下降，更新\n",
    "        bu[uid] += gamma * (eui - Lambda * bu[uid])  \n",
    "        bi[iid] += gamma * (eui - Lambda * bi[iid])\n",
    "                \n",
    "        temp = qi[iid]  \n",
    "        qi[iid] += gamma * (eui * pu[uid] - Lambda * qi[iid])\n",
    "        pu[uid] += gamma * (eui * temp - Lambda * pu[uid])\n",
    "            \n",
    "    # 学习率递减\n",
    "    gamma = gamma * 0.93\n",
    "    each_rmse = np.sqrt(rmse_sum / n_records)\n",
    "    \n",
    "    each_time_tick = time.time()\n",
    "    each_cost_time = each_time_tick - each_time_start\n",
    "    each_time_start = each_time_tick\n",
    "\n",
    "    print(\"完成第{}个step的训练, rmse={}, 耗时{:.4f}秒\".format(\n",
    "        step + 1, each_rmse, each_cost_time))\n",
    "\n",
    "time_end = time.time()\n",
    "total_cost_time = time_end - time_start\n",
    "print(\"结束了{}个step的训练，总耗时{:.4f}秒\".format(steps, total_cost_time))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 保存模型参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# A method for saving object data to JSON file\n",
    "def save_json(filepath):\n",
    "    dict_ = dict()\n",
    "    dict_['mu'] = mu\n",
    "    dict_['K'] = K\n",
    "    \n",
    "    dict_['bi'] = bi.tolist()\n",
    "    dict_['bu'] = bu.tolist()\n",
    "    \n",
    "    dict_['qi'] = qi.tolist()\n",
    "    dict_['pu'] = pu.tolist()\n",
    "\n",
    "    # Creat json and save to file\n",
    "    json_txt = json.dumps(dict_)\n",
    "    with open(filepath, 'w') as file:\n",
    "        file.write(json_txt)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# A method for loading data from JSON file\n",
    "def load_json(filepath):\n",
    "    with open(filepath, 'r') as file:\n",
    "        dict_ = json.load(file)\n",
    "\n",
    "        mu = dict_['mu']\n",
    "        K = dict_['K']\n",
    "\n",
    "        bi = np.asarray(dict_['bi'])\n",
    "        bu = np.asarray(dict_['bu'])\n",
    "    \n",
    "        qi = np.asarray(dict_['qi'])\n",
    "        pu = np.asarray(dict_['pu'])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "save_json('./out/svd_model.json')\n",
    "load_json('./out/svd_model.json')\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 测试"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 对给定用户，推荐物品/计算打分"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def recommend(user):\n",
    "    \"\"\"\n",
    "    返回推荐items及其打分（DataFrame）\n",
    "    :param user: 输出User的userId\n",
    "    :return: 推荐结果DataFrame, 包含item_id和score\n",
    "    \"\"\"\n",
    "    cur_user_id = users_index[user]\n",
    "    \n",
    "    # 训练集中该用户打过分的item\n",
    "    cur_user_items = user_items[cur_user_id]\n",
    "\n",
    "    # 该用户对所有item的打分\n",
    "    user_items_scores = np.zeros(n_items)\n",
    "\n",
    "    # 预测打分\n",
    "    for i in range(n_items):\n",
    "        if i not in cur_user_items:\n",
    "            user_items_scores[i] = svd_pred(cur_user_id, i)\n",
    "    \n",
    "    # 推荐\n",
    "    sort_list = [(e, i) for i, e in enumerate(list(user_items_scores))]\n",
    "    sort_index = sorted(sort_list, reverse=True)\n",
    "    \n",
    "    # 创建DataFrame, 返回推荐列表\n",
    "    columns = ['item_id', 'score']\n",
    "    df = pd.DataFrame(columns=columns)\n",
    "\n",
    "    for each_item_score, each_item_index in sort_index:\n",
    "        if np.isnan(each_item_score):\n",
    "            continue\n",
    "        \n",
    "        if each_item_index in cur_user_items:\n",
    "            continue\n",
    "        \n",
    "        each_item_key_index = list(items_index.values()).index(each_item_index)\n",
    "        each_item_id = list(items_index.keys())[each_item_key_index]\n",
    "        df.loc[len(df)] = [each_item_id, each_item_score]\n",
    "    \n",
    "    return df\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 读取测试数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   user_id  item_id  rating  timestamp\n",
      "0        1        6       5  887431973\n",
      "1        1       10       3  875693118\n",
      "2        1       12       5  878542960\n",
      "3        1       14       5  874965706\n",
      "4        1       17       3  875073198\n"
     ]
    }
   ],
   "source": [
    "# 读取测试数据\n",
    "triplet_cols = ['user_id', 'item_id', 'rating', 'timestamp'] \n",
    "\n",
    "dpath = './data/u1.test'\n",
    "df_triplet_test = pd.read_csv(dpath,\n",
    "                              sep='\\t', \n",
    "                              names=triplet_cols, \n",
    "                              encoding='latin-1')\n",
    "print(df_triplet_test.head())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 测试，并计算评价指标\n",
    "PR、覆盖度、RMSE"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "def recommend_users(user_ids):\n",
    "    \"\"\"\n",
    "    为指定一批User推荐Item, 并返回推荐结果\n",
    "    :param user_ids: userId列表\n",
    "    :return: \n",
    "    \"\"\"\n",
    "    userid_rec_results = dict()\n",
    "    \n",
    "    time_start = time.time()\n",
    "    each_time_start = time_start\n",
    "    count = 0\n",
    "    \n",
    "    print(\"开始对{}个User计算推荐结果\".format(len(user_ids)))\n",
    "    for user_id in user_ids:\n",
    "        count = count + 1\n",
    "        if user_id not in users_index:\n",
    "            print(\"{} is a new user.\".format(user_id))\n",
    "            continue\n",
    "        \n",
    "        each_rec_items = recommend(user_id)\n",
    "        userid_rec_results[user_id] = each_rec_items\n",
    "        \n",
    "        if count % 100 == 0:\n",
    "            each_time_tick = time.time()\n",
    "            each_cost_time = each_time_tick - each_time_start\n",
    "            each_time_start = each_time_tick\n",
    "            print(\"user_index:{}, each_cost_time:{}\".format(\n",
    "                    count - 1, each_cost_time))\n",
    "            \n",
    "    time_end = time.time()\n",
    "    total_cost_time = time_end - time_start\n",
    "    print(\"完成{}个User的推荐, 共计耗时{}秒\".format(\n",
    "        count, total_cost_time\n",
    "    ))\n",
    "\n",
    "    return userid_rec_results\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "开始对459个User计算推荐结果\n",
      "user_index:99, each_cost_time:197.35128784179688\n",
      "user_index:199, each_cost_time:198.34334468841553\n",
      "user_index:299, each_cost_time:195.94120740890503\n",
      "user_index:399, each_cost_time:193.48006629943848\n",
      "完成459个User的推荐, 共计耗时896.7402906417847秒\n"
     ]
    }
   ],
   "source": [
    "# 测试集中的user_id集合\n",
    "unique_users_test = df_triplet_test['user_id'].unique()\n",
    "total_rec_results = recommend_users(unique_users_test)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "def evaluate(userid_rec_results, n_rec_items):\n",
    "    \"\"\"\n",
    "    为每个User截取若干条推荐结果，并衡量全体User的推荐效果\n",
    "    :param userid_rec_results:  推荐结果<userId -- 该user被推荐的全部Item>\n",
    "    :param n_rec_items:         每个所需截取的推荐结果的数量\n",
    "    :return: \n",
    "    \"\"\"\n",
    "    n_hits = 0              # TP\n",
    "    n_total_rec_items = 0   # TP+FP\n",
    "    n_total_test_items = 0  # TP+FN\n",
    "    all_rec_items = set()   # 所有User被推荐的Item的汇总\n",
    "    rss_test = 0.0          # 所有User的预测残差平方和\n",
    "\n",
    "    for user_id, rec_items in userid_rec_results.items():\n",
    "        user_records_test = df_triplet_test[df_triplet_test.user_id == user_id]\n",
    "        \n",
    "        # 累积TP和汇总所有User被推荐的指定数量的Item\n",
    "        for i in range(n_rec_items):\n",
    "            item_id = rec_items.iloc[i]['item_id']\n",
    "            if item_id in user_records_test['item_id'].values:\n",
    "                n_hits = n_hits + 1\n",
    "            all_rec_items.add(item_id)\n",
    "\n",
    "        # 累积预测评分残差平方和\n",
    "        for i in range(user_records_test.shape[0]):\n",
    "            item = user_records_test.iloc[i]['item_id']\n",
    "            score = user_records_test.iloc[i]['rating']\n",
    "            \n",
    "            df1 = rec_items[rec_items.item_id == item]\n",
    "            if df1.shape[0] == 0:\n",
    "                print(\"{} is a new item.\".format(item))\n",
    "                continue\n",
    "            \n",
    "            pred_score = df1['score'].values[0]\n",
    "            rss_test = rss_test + (pred_score - score)**2\n",
    "    \n",
    "        # 推荐的item总数(TP+FP)\n",
    "        n_total_rec_items = n_total_rec_items + n_rec_items\n",
    "    \n",
    "        # 真实item的总数(TP+FN)\n",
    "        n_total_test_items = n_total_test_items + user_records_test.shape[0]\n",
    "        \n",
    "    # Precision & Recall\n",
    "    precision = n_hits / (1.0 * n_total_rec_items)\n",
    "    recall = n_hits / (1.0 * n_total_test_items)\n",
    "    \n",
    "    # 覆盖度：推荐商品占总需要推荐商品的比例\n",
    "    coverage = len(all_rec_items) / (1.0 * n_items)\n",
    "    \n",
    "    # 打分的均方误差\n",
    "    rmse = np.sqrt(rss_test / df_triplet_test.shape[0])\n",
    "    \n",
    "    print(\"n_rec_items={}时:\\n \\tprecision={}\\n \"\n",
    "          \"\\trecall={}\\n \\tcoverage={}\\n \\trmse={}\".format(n_rec_items, \n",
    "                                                           precision, \n",
    "                                                           recall, \n",
    "                                                           coverage, \n",
    "                                                           rmse))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "推荐10个电影时的结果:\n",
      "599 is a new item.\n",
      "711 is a new item.\n",
      "814 is a new item.\n",
      "830 is a new item.\n",
      "852 is a new item.\n",
      "857 is a new item.\n",
      "1156 is a new item.\n",
      "1236 is a new item.\n",
      "1309 is a new item.\n",
      "1310 is a new item.\n",
      "1320 is a new item.\n",
      "1343 is a new item.\n",
      "1348 is a new item.\n",
      "1364 is a new item.\n",
      "1373 is a new item.\n",
      "1457 is a new item.\n",
      "1458 is a new item.\n",
      "1492 is a new item.\n",
      "1493 is a new item.\n",
      "1498 is a new item.\n",
      "1505 is a new item.\n",
      "1520 is a new item.\n",
      "1533 is a new item.\n",
      "1536 is a new item.\n",
      "1543 is a new item.\n",
      "1557 is a new item.\n",
      "1561 is a new item.\n",
      "1562 is a new item.\n",
      "1563 is a new item.\n",
      "1565 is a new item.\n",
      "1582 is a new item.\n",
      "1586 is a new item.\n",
      "n_rec_items=10时:\n",
      " \tprecision=0.07559912854030501\n",
      " \trecall=0.01735\n",
      " \tcoverage=0.09575757575757576\n",
      " \trmse=0.9247687112120774\n",
      "\n",
      "\n",
      "推荐20个电影时的结果\n",
      "599 is a new item.\n",
      "711 is a new item.\n",
      "814 is a new item.\n",
      "830 is a new item.\n",
      "852 is a new item.\n",
      "857 is a new item.\n",
      "1156 is a new item.\n",
      "1236 is a new item.\n",
      "1309 is a new item.\n",
      "1310 is a new item.\n",
      "1320 is a new item.\n",
      "1343 is a new item.\n",
      "1348 is a new item.\n",
      "1364 is a new item.\n",
      "1373 is a new item.\n",
      "1457 is a new item.\n",
      "1458 is a new item.\n",
      "1492 is a new item.\n",
      "1493 is a new item.\n",
      "1498 is a new item.\n",
      "1505 is a new item.\n",
      "1520 is a new item.\n",
      "1533 is a new item.\n",
      "1536 is a new item.\n",
      "1543 is a new item.\n",
      "1557 is a new item.\n",
      "1561 is a new item.\n",
      "1562 is a new item.\n",
      "1563 is a new item.\n",
      "1565 is a new item.\n",
      "1582 is a new item.\n",
      "1586 is a new item.\n",
      "n_rec_items=20时:\n",
      " \tprecision=0.07962962962962963\n",
      " \trecall=0.03655\n",
      " \tcoverage=0.15333333333333332\n",
      " \trmse=0.9247687112120774\n"
     ]
    }
   ],
   "source": [
    "# 分别计算推荐10个电影和20个电影时的precision/recall/coverage/rmse\n",
    "print(\"\\n推荐10个电影时的结果:\")\n",
    "evaluate(total_rec_results, 10)\n",
    "\n",
    "print(\"\\n\\n推荐20个电影时的结果\")\n",
    "evaluate(total_rec_results, 20)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
